<template>
  <div style="position: absolute; left: 6rem; margin-top: 42px; background-color: white">
    <el-container>
      <el-container style="width: max-content">
        <!-- 上面6个表格 -->
        <el-header
          style="
            padding: 10px;
            display: flex;
            justify-content: space-between;
            height: 400px;
            overflow-x: auto;
            max-width: 1800px;
          "
        >
          <div
            v-for="(tableData, index) in topTables"
            :key="index"
            style="width: 400px; margin-right: 10px"
          >
            <el-table
              ref="multipleTop"
              :data="tableData"
              stripe
              border
              :height="childTableHeight + 'px'"
              :max-height="childTableHeight + 'px'"
              :cell-style="cellStyle1"
              @selection-change="handleSelectionChange(index)"
              :header-cell-style="headerCellStyle1"
            >
              <!-- <el-table-column type="selection" width="55" align="center"
               /> -->
              <el-table-column width="50" align="center">
                <template #header>
                  <div class="custom-header">{{ topGx[index] }}</div>
                </template>
                <template #default="{ row }">
                  <el-checkbox v-model="row.isTrue" />
                </template>
              </el-table-column>
              <!-- <el-table-column prop="process" label="工序" align="center">
                <template #default="scope">
                  <span
                    v-if="
                      scope.row.process !== undefined &&
                      processDescription[scope.row.process]
                    "
                  >
                    {{ processDescription[scope.row.process] }}
                  </span>
                  <span v-else> 数据加载中... </span>
                </template>
              </el-table-column> -->

              <el-table-column label="卡号" width="100" align="center" v-if="index == 0">
                <template #default="{ row }">
                  <el-input v-model="row.card_number" />
                </template>
              </el-table-column>
              <el-table-column label="卡号" width="100" align="center" v-if="index != 0">
                <template #default="{ row }">
                  {{ row.card_number }}
                </template>
              </el-table-column>
              <el-table-column label="天数" width="40" align="center">
                <template #default="{ row }">
                  {{ row.days }}
                </template>
              </el-table-column>
              <el-table-column label="日期" width="80" align="center" v-if="index === 0">
                <template #default="{ row }">
                  {{ row.date_time }}
                </template>
              </el-table-column>

              <el-table-column label="重量" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.weight" />
                </template>
              </el-table-column>

              <!--<el-table-column label="厚度" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.thickness" />
                </template>
              </el-table-column> 
              <el-table-column label="宽度" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.width" />
                </template>
              </el-table-column>-->
              <el-table-column label="原料规格" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.raw_ms" />
                </template>
              </el-table-column>
              <el-table-column label="小分条规格" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.ls_ms" />
                </template>
              </el-table-column>
              <el-table-column label="备注" width="200" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.remark" />
                </template>
              </el-table-column>

              <el-table-column label="操作" width="100" align="center" v-if="index === 0">
                <template #default="{ $index, row }">
                  <el-button
                    @click="deleteRow(index, $index, 'top')"
                    type="danger"
                    size="small"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 添加一行按钮 -->
            <el-button
              @click="addRow(index)"
              v-if="index === 0"
              type="primary"
              size="small"
              style="margin-top: 5px"
            >
              添加一行
            </el-button>
            <!-- 转移按钮 -->

            <el-button
              @click="transferRowsLeft(index, 'top')"
              type="success"
              size="small"
              style="margin-top: 5px"
            >
              左移
            </el-button>
            <el-button
              @click="transferRows(index, 'top')"
              type="success"
              size="small"
              style="margin-top: 5px"
            >
              右移
            </el-button>
            <el-button
              v-if="index === 0"
              size="small"
              style="margin-top: 5px"
              type="primary"
              @click="getAllData()"
              >保存</el-button
            >
          </div>
        </el-header>

        <!-- 下面6个表格 -->
        <el-main
          style="
            padding: 10px;
            display: flex;
            justify-content: space-between;
            height: 400px;
            overflow-x: auto;
            max-width: 1800px;
          "
        >
          <div
            v-for="(tableData, index) in bottomTables"
            :key="index"
            style="width: 400px; margin-right: 10px"
          >
            <el-table
              ref="multipleButtom"
              :data="tableData"
              stripe
              border
              :height="childTableHeight + 'px'"
              :max-height="childTableHeight + 'px'"
              :cell-style="cellStyle1"
              @selection-change="handleSelectionChangeBottom(index)"
              :header-cell-style="headerCellStyle1"
            >
              <!-- <el-table-column :label="bottomGx[index]" width="100" align="center">
                <template #default="{ row }">
                  <el-checkbox v-model="row.isTrue" />
                </template>
              </el-table-column>
          -->
              <el-table-column width="100" align="center">
                <template #header>
                  <div class="custom-header">{{ bottomGx[index] }}</div>
                </template>
                <template #default="{ row }">
                  <el-checkbox v-model="row.isTrue" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="卡号" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.card_number" />
                </template>
              </el-table-column> -->
              <el-table-column label="卡号" width="100" align="center">
                <template #default="{ row }">
                  {{ row.card_number }}
                </template>
              </el-table-column>
              <el-table-column label="天数" width="40" align="center">
                <template #default="{ row }">
                  {{ row.days }}
                </template>
              </el-table-column>
              <!-- <el-table-column label="日期" width="80" align="center" v-if="index === 0">
                <template #default="{ row }">
                  {{ row.date_time }}
                </template>
              </el-table-column> -->
              <el-table-column label="重量" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.weight" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="厚度" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.thickness" />
                </template>
              </el-table-column>
              <el-table-column label="宽度" width="50" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.width" />
                </template>
              </el-table-column> -->
              <el-table-column label="原料规格" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.raw_ms" />
                </template>
              </el-table-column>
              <el-table-column label="小分条规格" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.ls_ms" />
                </template>
              </el-table-column>
              <el-table-column label="备注" width="200" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.remark" />
                </template>
              </el-table-column>
              <el-table-column label="操作事件" width="100" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.days" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center" v-if="index === 0">
                <template #default="{ $index, row }">
                  <el-button
                    @click="deleteRow(index, $index, 'bottom')"
                    type="danger"
                    size="small"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 添加一行按钮 -->
            <!-- <el-button
              @click="addRowBottom(index)"
              type="primary"
              size="small"
              style="margin-top: 5px"
            >
              添加一行
            </el-button> -->
            <!-- 转移按钮 -->

            <el-button
              @click="transferRowsLeft(index, 'bottom')"
              type="success"
              size="small"
              style="margin-top: 5px"
            >
              左移
            </el-button>
            <el-button
              @click="transferRows(index, 'bottom')"
              type="success"
              size="small"
              style="margin-top: 5px"
            >
              右移
            </el-button>
            <!-- <el-button
              size="small"
              style="margin-top: 5px"
              type="primary"
              @click="getAllData()"
              >保存</el-button
            > -->
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import moment from "moment";
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import * as newCrud from "../../components/utils/newCrud.ts";
import * as notifications from "../../components/utils/notification.ts";
import Co from "../../components/utils/t-ui-plus-dev/packages/select-table/src/index.vue";
const processDescription = {
  1: "轧机",
  2: "退火",
  3: "拉矫",
  4: "分条",
  5: "清洗线",
  6: "破带",
  7: "大分条",
  8: "去应力",
  9: "贴膜",
  10: "研磨",
  11: "切边",
  0: "入库",
};
const topGx = {
  0: "大分条",
  1: "轧机",
  2: "退火",
  3: "拉矫",
};
const bottomGx = {
  0: "去应力",
  1: "清洗线",
  2: "分条",
  3: "入库",
};
const multipleTopProcess = [7, 1, 2, 3];
const bottomTablesProcess = [8, 5, 4, 0];
// 默认数据结构
const defaultRowData = {
  isTrue: false,
  card_number: "",
  weight: "",
  raw_ms: "",
  ls_ms: "",
  remark: "",
  thickness: "",
  width: "",
  process: "",
  days: "",
  date_time: "",
};
const multipleTop = ref();
const multipleButtom = ref();

// 上面6个表格数据
const topTables = ref([
  [{ ...defaultRowData, process: 7 }],
  [{ ...defaultRowData, process: 1 }],
  [{ ...defaultRowData, process: 2 }],
  [{ ...defaultRowData, process: 3 }],
]);

// 下面6个表格数据
const bottomTables = ref([
  [{ ...defaultRowData, process: 8 }],
  [{ ...defaultRowData, process: 5 }],
  [{ ...defaultRowData, process: 4 }],
  [{ ...defaultRowData, process: 0 }],
]);

// 存储选中的行
const selectedRowsTop = ref<any[]>([]);
const selectedRowsBottom = ref<any[]>([]);

// 添加一行到上面的表格
const addRow = (index: number) => {
  if (index == 0) {
    topTables.value[index].push({
      ...defaultRowData,
      process: 7,
    });
  }
  if (index == 1) {
    topTables.value[index].push({
      ...defaultRowData,
      process: 1,
    });
  }
  if (index == 2) {
    topTables.value[index].push({
      ...defaultRowData,
      process: 2,
    });
  }
  if (index == 3) {
    topTables.value[index].push({
      ...defaultRowData,
      process: 3,
    });
  }
};

// 添加一行到下面的表格
const addRowBottom = (index: number) => {
  if (index == 0) {
    bottomTables.value[index].push({
      ...defaultRowData,
      process: 8,
    });
  }
  if (index == 1) {
    bottomTables.value[index].push({
      ...defaultRowData,
      process: 5,
    });
  }
  if (index == 2) {
    bottomTables.value[index].push({
      ...defaultRowData,
      process: 4,
    });
  }
  if (index == 3) {
    bottomTables.value[index].push({
      ...defaultRowData,
      process: 0,
    });
  }
};

// 处理选择行的逻辑
const selectedRows = ref([]);
const handleSelectionChange = (index: number) => (selectedRows: any[]) => {
  //   selectedRowsTop.value[index] = selectedRows;
};

const handleSelectionChangeBottom = (index: number) => (selectedRows: any[]) => {
  //   selectedRowsBottom.value[index] = selectedRows;
};
const text = async () => {
  const getPro = await newCrud.fetchData("/Process/getProcess", "post", {});
  addRowByProcess(getPro.info);
};
onBeforeMount(() => {
  text();
});

// 保存
const getAllData = async () => {
  const userName = Cookies.get("userName");
  const res = await crud.fetchData("UserDe/getUserDe", "post", {
    input5: userName,
  });
  const timestamp = new Date().getTime();
  const fdateTime = moment(timestamp).format("YYYY-MM-DD HH:mm:ss");
  const fdate = moment(timestamp).format("YYYY-MM-DD");

  // 操作人员相关信息
  const date_time = fdate;
  const operator_id = res[0].userId;
  const operator_name = res[0].userName;
  const operation_time = fdateTime;

  // 封装 multipleTop 的数据
  const topTablesData = multipleTop.value.map((table, index) => {
    return table.data
      .filter((row) => row.card_number) // 过滤掉 card_number 为 null 或空的行
      .map((row) => {
        return {
          card_number: row.card_number,
          weight: row.weight,
          raw_ms: row.raw_ms,
          ls_ms: row.ls_ms,
          remark: row.remark,
          thickness: row.thickness,
          width: row.width,
          process: row.process,
          isTrue: row.isTrue,
          //  days: row.days || fdate,
          days: row.days,
          date_time: row.date_time,
          operator_id: operator_id,
          operator_name: operator_name,
          operation_time: operation_time,
          table_index: `top-${index}`, // 记录表格的索引，区分 top 和 bottom
        };
      });
  });

  // 封装 multipleButtom 的数据
  const bottomTablesData = multipleButtom.value.map((table, index) => {
    return table.data
      .filter((row) => row.card_number) // 过滤掉 card_number 为 null 或空的行
      .map((row) => {
        return {
          card_number: row.card_number,
          weight: row.weight,
          raw_ms: row.raw_ms,
          ls_ms: row.ls_ms,
          remark: row.remark,
          thickness: row.thickness,
          width: row.width,
          process: row.process,
          isTrue: row.isTrue,
          //  days: row.days || fdate,
          days: row.days,
          date_time: row.date_time,
          operator_id: operator_id,
          operator_name: operator_name,
          operation_time: operation_time,
          table_index: `bottom-${index}`, // 记录表格的索引
        };
      });
  });

  // 将 top 和 bottom 的数据合并到一起
  const allData = [...topTablesData.flat(), ...bottomTablesData.flat()];
  //重复校验
  const cardNumbers = allData.map((item) => item.card_number);
  const duplicates = cardNumbers.filter(
    (item, index) => cardNumbers.indexOf(item) !== index
  );

  if (duplicates.length > 0) {
    notifications.showMessage("卡号重复", "error");
    return; // 终止后续操作
  }
  const jsonObj = {
    entity: allData.map((item, index) => {
      return { ...item, row_num: (index + 1).toString() };
    }),
  };
  const pro = await newCrud.sendRequest("/Process/iuProcess", "post", jsonObj);

  if (pro.code == 200 || pro.code == 1) {
    const getPro = await newCrud.fetchData("/Process/getProcess", "post", {});
    addRowByProcess(getPro.info);
  }
};
// 右
const transferRows = (index: number, from: string) => {
  if (from === "top") {
    const tableData = multipleTop.value[index].data;
    const trueRows = tableData.filter((row: any) => row.isTrue === true);

    for (let i = tableData.length - 1; i >= 0; i--) {
      if (tableData[i].isTrue === true) {
        tableData.splice(i, 1); // 删除满足条件的行
      }
    }

    if (index != 3) {
      trueRows.forEach((row: any) => {
        row.process = multipleTopProcess[index + 1];
      });
      multipleTop.value[index + 1].data.push(...trueRows);
      getAllData();
      return;
    }
    trueRows.forEach((row: any) => {
      row.process = 8;
    });
    multipleButtom.value[0].data.push(...trueRows);
    getAllData();
    return;
  }
  const tableDataBottm = multipleButtom.value[index].data;
  const trueRows = tableDataBottm.filter((row: any) => row.isTrue === true);
  for (let i = tableDataBottm.length - 1; i >= 0; i--) {
    if (tableDataBottm[i].isTrue === true) {
      tableDataBottm.splice(i, 1); // 删除满足条件的行
    }
  }
  if (index != 3) {
    trueRows.forEach((row: any) => {
      row.process = bottomTablesProcess[index + 1];
    });
    multipleButtom.value[index + 1].data.push(...trueRows);
    getAllData();
    return;
  }
  trueRows.forEach((row: any) => {
    row.process = bottomTablesProcess[index + 1];
  });
  multipleButtom.value[3].data.push(...trueRows);
  getAllData();
  return;
};
//左
const transferRowsLeft = (index: number, from: string) => {
  if (from == "top") {
    const tableData = multipleTop.value[index].data;
    const trueRows = tableData.filter((row: any) => row.isTrue === true);

    for (let i = tableData.length - 1; i >= 0; i--) {
      if (tableData[i].isTrue === true) {
        tableData.splice(i, 1); // 删除满足条件的行
      }
    }
    if (index != 0) {
      trueRows.forEach((row: any) => {
        row.process = multipleTopProcess[index - 1];
      });
      multipleTop.value[index - 1].data.push(...trueRows);
      getAllData();

      return;
    }
    trueRows.forEach((row: any) => {
      row.process = 7;
    });
    multipleTop.value[0].data.push(...trueRows);
    getAllData();

    return;
  }
  const tableDataBottm = multipleButtom.value[index].data;
  const trueRows = tableDataBottm.filter((row: any) => row.isTrue === true);
  //   trueRows.forEach((row: any) => {
  //     row.days = fdateTime;
  //   });
  for (let i = tableDataBottm.length - 1; i >= 0; i--) {
    if (tableDataBottm[i].isTrue === true) {
      tableDataBottm.splice(i, 1); // 删除满足条件的行
    }
  }
  if (index != 0) {
    trueRows.forEach((row: any) => {
      row.process = bottomTablesProcess[index - 1];
    });
    multipleButtom.value[index - 1].data.push(...trueRows);
    getAllData();

    return;
  }
  trueRows.forEach((row: any) => {
    row.process = 3;
  });
  multipleTop.value[3].data.push(...trueRows);
  getAllData();
  return;
};
// 删除一行的逻辑
const deleteRow = (tableIndex: number, rowIndex: number, from: string) => {
  if (from === "top") {
    topTables.value[tableIndex].splice(rowIndex, 1); // 删除对应行
  } else if (from === "bottom") {
    bottomTables.value[tableIndex].splice(rowIndex, 1); // 删除对应行
  }
};

// 表格样式
const cellStyle1 = () => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};

const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "bold",
  color: "#1F2129",
  height: "40px",
  margin: 0,
  padding: 0,
  textAlign: "center",
};

// 表格高度
const childTableHeight = ref(350);
const addRowByProcess = (data) => {
  // 先清空所有表格中的数据
  multipleTopProcess.forEach((process, index) => {
    multipleTop.value[index].data.splice(0, multipleTop.value[index].data.length);
  });

  bottomTablesProcess.forEach((process, index) => {
    multipleButtom.value[index].data.splice(0, multipleButtom.value[index].data.length);
  });

  // 然后再依次添加新的数据
  data.forEach((item) => {
    const { process } = item;
    let index;

    if (multipleTopProcess.includes(process)) {
      index = multipleTopProcess.indexOf(process);
      // 创建一个新对象，设置 isTrue 为 false
      const newItem = { ...item, isTrue: false };
      // 添加新数据
      multipleTop.value[index].data.push(newItem);
    } else if (bottomTablesProcess.includes(process)) {
      index = bottomTablesProcess.indexOf(process);
      // 创建一个新对象，设置 isTrue 为 false
      const newItem = { ...item, isTrue: false };
      // 添加新数据
      multipleButtom.value[index].data.push(newItem);
    }
  });
};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
.custom-header {
  color: blue;
}
</style>
